package cn.snews.Servlet;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import news.Comments;
import news.News;
import news.topic;
import dao.CommentsDAO;
import dao.NewsDAO;
import dao.TopicDAO;

public class NewsServlet extends HttpServlet {

	private static final long serialVersionUID = 7698264302150981924L;

	public NewsServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		Integer nid = Integer.parseInt(request.getParameter("nid"));
		String ccontent = request.getParameter("ccontent");
		if (ccontent != null) {
			Comments c = new Comments();
			String cauthor = request.getParameter("cauthor");
			String cip = request.getParameter("cip");
			SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
			try {
				c.setCdate(sdf.parse(sdf.format(new Date())));
			} catch (Exception e) {
				e.printStackTrace();
			}
			c.setCip(cip);
			c.setCnid(nid);
			c.setCauthor(cauthor);
			c.setConntent(ccontent);
			CommentsDAO.DAO.insert(c);
		}

		List<News> n = null;
		Map<topic, List<News>> map = new HashMap<topic, List<News>>();

		List<topic> t = TopicDAO.showIndex();
		for (topic top : t) {
			n = NewsDAO.find(0, 6, (top.getTid()));
			map.put(top, n);
		}

		News news = NewsDAO.showNews(nid);
		List<Comments> li = CommentsDAO.showComments(nid);

		request.setAttribute("news", news);// 显示单个新闻
		request.setAttribute("li", li);// 显示评论的集合
		request.setAttribute("map", map);
		request.setAttribute("nid", nid);
		request.getRequestDispatcher("/WEB-INF/jsp/news.jsp").forward(request,
				response);
	}

	public void init() throws ServletException {
	}
}
